package cn.cloud.butler.uploadapi.service;

import cn.cloud.butler.uploadapi.domain.ProduceSumEntity;
import cn.cloud.butler.uploadapi.repository.ProduceSumRepository;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

@Service
public class ProduceSumService {

    @Autowired
    ProduceSumRepository produceSumRepository;

    /**
     * 保存今日之前的系统加工件数
     * @param macsn 机床sn号
     * @param data 扫码上传数据
     * @param uploadtime 上传时间
     * @return int
     */
    @Transactional
    public int saveProduceSum(String macsn, JSONArray data, String uploadtime){
        int m = 0;
        for(int i = 0; i<data.size();i++){
            JSONObject partInfo = data.getJSONObject(i);
            String producename = partInfo.getString("gcode");

            ProduceSumEntity produceSum = new ProduceSumEntity();
            produceSum.setMacSn(macsn);
            produceSum.setProduceName(partInfo.getString("gcode"));
            produceSum.setProNum((long)partInfo.getIntValue("count"));
            produceSum.setUploadTime(uploadtime);

            try {
                ProduceSumEntity existProduceSums = produceSumRepository.selExistProduceSum(uploadtime,macsn,producename);
                if(existProduceSums == null){
                    m = produceSumRepository.saveAndFlush(produceSum).getiD().intValue();
                }else{
                    produceSum.setiD(existProduceSums.getiD());
                    m = produceSumRepository.saveAndFlush(produceSum).getiD().intValue();
                }
            }catch (Exception e){
                m = -2;
            }
        }
        return m;
    }
}
